// ==UserScript==
// @name         bd_movie
// @namespace    http://tampermonkey.net/
// @version      0.2
// @description  try to take over the world!
// @author       You
// @match        https://www.bd-film.cc/*
// @require        https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js
// @grant        GM_xmlhttpRequest
// @grant        GM_setClipboard
// ==/UserScript==
// eg https://www.bd-film.cc/search.jspx?q=tt0212985 ed2k baidu
// eg https://www.bd-film.cc/search.jspx?q=%E6%AD%A3%E4%B9%89%E7%9A%84%E6%85%88%E6%82%B2 ed2k*5 uc baidu
(function () {
    'use strict';
    /*************************Base64编码开始*******************************/
    function utf8ToUtf16(s) {
        if (!s) {
            return;
        }
        var i, codes, bytes, ret = [],
            len = s.length;
        for (i = 0; i < len; i++) {
            codes = [];
            codes.push(s.charCodeAt(i));
            if (((codes[0] >> 7) & 0xff) == 0x0) {
                // 单字节 0xxxxxxx
                ret.push(s.charAt(i));
            } else if (((codes[0] >> 5) & 0xff) == 0x6) {
                // 双字节 110xxxxx 10xxxxxx
                codes.push(s.charCodeAt(++i));
                bytes = [];
                bytes.push(codes[0] & 0x1f);
                bytes.push(codes[1] & 0x3f);
                ret.push(String.fromCharCode((bytes[0] << 6) | bytes[1]));
            } else if (((codes[0] >> 4) & 0xff) == 0xe) {
                // 三字节 1110xxxx 10xxxxxx 10xxxxxx
                codes.push(s.charCodeAt(++i));
                codes.push(s.charCodeAt(++i));
                bytes = [];
                bytes.push((codes[0] << 4) | ((codes[1] >> 2) & 0xf));
                bytes.push(((codes[1] & 0x3) << 6) | (codes[2] & 0x3f));
                ret.push(String.fromCharCode((bytes[0] << 8) | bytes[1]));
            }
        }
        return ret.join('');
    }

    var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    function decode64(input) {
        var output = "";
        var chr1, chr2, chr3 = "";
        var enc1, enc2, enc3, enc4 = "";
        var i = 0;

        if (input.length % 4 != 0) {
            return "";
        }
        var base64test = /[^A-Za-z0-9\+\/\=]/g;
        if (base64test.exec(input)) {
            return "";
        }

        do {
            enc1 = keyStr.indexOf(input.charAt(i++));
            enc2 = keyStr.indexOf(input.charAt(i++));
            enc3 = keyStr.indexOf(input.charAt(i++));
            enc4 = keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output += String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output += String.fromCharCode(chr3);
            }

            chr1 = chr2 = chr3 = "";
            enc1 = enc2 = enc3 = enc4 = "";

        } while (i < input.length);

        return output;
    }

    /**************************Base64编码结束*******************************/

    function getFirstLink() {

        let linkDom = document.querySelector("#content_list > li.list-item > div > a")
        if (!linkDom) {
            return;
        }
        let link = linkDom.getAttribute('href');
        if (!link) {
            return;
        }
        GM_xmlhttpRequest({
            url: link,
            timeout: 45e3,
            onload: function (res) {
                let response = page_parser(res.responseText)
                getDownloadUrl(response)
            }
        })

    }

    function page_parser(responseText) {
        // 替换一些信息防止图片和页面脚本的加载，同时可能加快页面解析速度
        responseText = responseText.replace(/s+src=/ig, ' data-src='); // 图片，部分外源脚本
        //responseText = responseText.replace(/<script[^>]*?>[\S\s]*?<\/script>/ig, ''); //页面脚本
        return (new DOMParser()).parseFromString(responseText, 'text/html');
    }

    function getDownloadUrl(dom) {
        let re = /var\surls\s=\s"([\S]*)"/gi
        let urls;

        //不得不做
        let urlsDom = dom.querySelectorAll('script');
        for(let i=0;i<urlsDom.length;i++) {
            let text = urlsDom[i].innerText;
            if(text.includes('urls')){
                urls = re.exec(text)[1] || '';
            }
        }

        let res = dom.querySelectorAll('#downlist>div.panel.clearfix>div.option>a')
        let text = decodeURIComponent(res[0].href);
        let ed2ks = unescape(utf8ToUtf16(decode64(urls.split("").reverse().join("")))).replace("<p>", "").replace("</p>", "").split("###");
        console.log('ed',ed2ks);
        let ed2k = ed2ks[0];
        GM_setClipboard(ed2k)
        let baidu = dom.querySelector('#downlist>div.panel.clearfix>div.option.copybtn.alert');
        if (baidu) {
            console.log(baidu.find('a').href, baidu.find('span').innerText)
        }
    }

    $(document).ready(function () {
        //getDownloadUrl()
        getFirstLink();
    })


})();
/**
 * Created by zqbinary on 2020/8/11.
 */
